<template>
  <div class="message-container">
    <div class="chat-layout">
      <!-- 左侧好友列表 -->
      <div class="friend-list">
        <div class="list-header">
          <div class="account-selector">
            <el-select 
              v-model="selectedAccount" 
              placeholder="选择账号" 
              size="small"
              @change="handleAccountChange"
              :loading="accountsLoading"
              style="width: 100%; margin-bottom: 12px;"
            >
              <template #prefix>
                <el-icon><UserFilled /></el-icon>
              </template>
              <template #empty>
                <div class="empty-data">
                  <p v-if="accountsLoading">正在加载账号列表...</p>
                  <p v-else>暂无在线账号</p>
                </div>
              </template>
              <el-option
                v-for="account in accountOptions"
                :key="account.id"
                :label="account.name"
                :value="account.id"
              >
                <div class="account-option">
                  <el-avatar :size="20" :src="account.avatar" class="account-avatar" />
                  <span>{{ account.name }}</span>
                </div>
              </el-option>
            </el-select>
          </div>
          <h3>好友列表</h3>
          <el-autocomplete
            v-model="searchQuery"
            :fetch-suggestions="querySearchFriends"
            placeholder="搜索好友（昵称/备注/标签）"
            value-key="nickname"
            :trigger-on-focus="false"
            @select="handleSelectSearchedFriend"
            size="small"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #default="{ item }">
              <div class="search-item" style="display:flex;align-items:center;gap:8px;">
                <el-avatar :size="20" :src="item.avatar" />
                <span class="name">{{ item.nickname || item.remark || item.wx_id }}</span>
                <span v-if="item.remark" style="color:#909399;">（{{ item.remark }}）</span>
                <el-tag v-if="item.tags && item.tags.length" size="small">{{ item.tags[0] }}</el-tag>
              </div>
            </template>
          </el-autocomplete>
        </div>
        
        <div class="friend-items">
          <div
            v-for="friend in sortedFriends"
            :key="friend.wx_id"
            :class="['friend-item', { active: selectedFriend?.wx_id === friend.wx_id, top: friend.isTop }]"
            @click="selectFriend(friend)"
          >
            <el-avatar :size="40" :src="friend.avatar" />
            <div class="friend-info">
              <div class="friend-name">{{ friend.nickname }}</div>
              <div class="last-message">{{ friend.lastMessage || '暂无消息' }}</div>
            </div>
            <el-badge v-if="getUnreadForFriend(friend.wx_id) > 0" :value="getUnreadForFriend(friend.wx_id)" class="unread-badge" />
            <el-tag v-if="friend.tags?.length" size="small">{{ friend.tags[0] }}</el-tag>
            <el-icon v-if="friend.isTop" class="top-icon"><ArrowUp /></el-icon>
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-area">
        <!-- 聊天头部 -->
        <div class="chat-header" v-if="selectedFriend" style="display:flex;justify-content:space-between;align-items:center;">
          <div class="chat-title" style="display:flex;align-items:center;gap:8px;">
            <el-avatar :size="32" :src="selectedFriend.avatar" />
            <span>{{ selectedFriend.nickname }}</span>
            <el-tag size="small" :type="selectedFriend.status === 'online' ? 'success' : 'info'">
              {{ selectedFriend.status === 'online' ? '在线' : '离线' }}
            </el-tag>
          </div>
          <div class="chat-actions">            
            <el-button type="primary" plain size="small" @click="generateSummary">生成摘要</el-button>
            <el-button type="danger" plain size="small" @click="openEditDialog">修改对话</el-button>
<!--            <el-button type="danger" plain size="small" @click="openQaDialog">查看问答</el-button>-->
            <el-button type="danger" plain size="small" :loading="deletingConv" @click="handleDeleteConversation">删除上下文</el-button>

          </div>
        </div>



        <el-dialog v-model="editDialogVisible" title="修改对话" width="600px">
          <el-form :model="qaForm" label-width="70px">
            <el-form-item label="模板">
              <el-select
                v-model="qaForm.template"
                placeholder="选择模板"
                style="width: 100%;"
                clearable
              >
                <el-option
                  v-for="template in templateOptions"
                  :key="template"
                  :label="template"
                  :value="template"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="问题1">
              <el-input v-model="qaForm.question1" placeholder="请输入问题" />
            </el-form-item>
            <el-form-item label="答案1">
              <el-input type="textarea" :rows="4" v-model="qaForm.answer1" placeholder="请输入答案" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="editDialogVisible = false">取消</el-button>
              <el-button type="primary" :loading="editSaving" @click="saveEditedDialog">保存</el-button>
            </span>
          </template>
        </el-dialog>
         
        <!-- 聊天消息区域 -->
        <div class="chat-messages" ref="messagesContainer">
          <div v-if="!selectedFriend" class="no-chat">
            <el-empty description="请选择好友开始聊天" />
          </div>
          
          <div v-else-if="chatMessages.length === 0" class="no-messages">
            <el-empty description="暂无聊天记录" />
          </div>
          
          <div v-else class="messages-list">
            <div
              v-for="(message, index) in chatMessages"
              :key="index"
              :class="['message-item', message.is_sent ? 'sent' : 'received']"
            >
              <div class="message-time">{{ formatMessageTime(message.timestamp) }}</div>
              <div class="message-content">
                <!-- 图片消息 -->
                <div v-if="message.type === 3" class="message-image">
                  <img 
                    :src="message.content" 
                    :alt="message.meta?.filename || '图片'"
                    @click="previewImage(message.content)"
                    @error="handleImageError"
                    class="chat-image"
                    :style="{
                      maxWidth: '200px',
                      maxHeight: '200px',
                      cursor: 'pointer'
                    }"
                  />
                  <div v-if="message.content === '图片上传中...'" class="upload-status">
                    <el-icon class="is-loading"><Loading /></el-icon>
                    上传中...
                  </div>
                </div>
                <!-- 文本消息 -->
                <div v-else class="message-text">{{ message.content }}</div>
                <div class="message-type">
                  <el-tag size="small" :type="getMessageTypeTag(message.type)">
                    {{ getMessageTypeText(message.type) }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入框区域 -->
        <div class="chat-input" v-if="selectedFriend">
          <!-- 隐藏的文件选择器 -->
          <input
            ref="imageFileInput"
            type="file"
            accept="image/*"
            style="display: none"
            @change="handleImageSelect"
          />
          <div class="input-toolbar">
            <el-button 
              type="text" 
              size="small" 
              @click="handleImageClick"
              :loading="uploadingImage"
              :disabled="uploadingImage"
            >
              <el-icon><Picture /></el-icon>
            </el-button>
            <el-button type="text" size="small">
              <el-icon><Microphone /></el-icon>
            </el-button>
            <el-button type="text" size="small">
              <el-icon><Folder /></el-icon>
            </el-button>
            <div class="switch-container">
              <el-switch 
                v-model="aiEnabled" 
                active-text="开启ai" 
                inactive-text="关闭ai" 
                @change="handleAiToggle"
              />
            </div>
          </div>
          <div class="input-area">
            <el-input
              v-model="messageInput"
              type="textarea"
              :rows="3"
              placeholder="请输入消息...（Enter发送，Shift+Enter换行）"
              resize="none"
              @keydown.enter.prevent="handleEnterSend"
            />
            <el-button type="primary" @click="sendMessage" :loading="sending">
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed, onBeforeUnmount, reactive } from 'vue'


import { Search, Picture, Microphone, Folder, UserFilled, ArrowUp, Loading } from '@element-plus/icons-vue'

import { ElMessage, ElMessageBox, ElSwitch } from 'element-plus'


import axios from 'axios'
import { socketService, IncomingMessagePayload } from '@/utils/socket'
import { messageStore } from '@/utils/messageStore'

interface Friend {
  wx_id: string
  nickname: string
  avatar: string
  status: 'online' | 'offline'
  lastMessage?: string 
  unreadCount: number
  tags?: string[]
  isTop: boolean
  lastMessageTimestamp?: string
  timestamp?: string
  remark?: string // 新增备注字段
}

interface Account {
  id: string
  name: string
  avatar: string
  status: 'online' | 'offline'
  auth_key: string
}

interface ChatMessage {
  id: string
  content: string
  timestamp: string
  type: number
  is_sent: boolean
  meta?: {
    width?: number
    height?: number
    size?: number
    filename?: string
    mime?: string
  }
}

const searchQuery = ref('')
const selectedFriend = ref<Friend | null>(null)
const chatMessages = ref<ChatMessage[]>([])
const messageInput = ref('')
const aiEnabled = ref(true)
const sending = ref(false)
const messagesContainer = ref<HTMLElement>()

// // 查看问答相关
// const qaDialogVisible = ref(false)
// const qaList = ref<any[]>([])
// const qaLoading = ref(false)

// 图片上传相关
const imageFileInput = ref<HTMLInputElement>()
const uploadingImage = ref(false)

// 修改对话弹窗
const editDialogVisible = ref(false)
const editSaving = ref(false)
// 当前编辑的问答ID
const currentEditingId = ref('')
const qaForm = reactive({ question1: '', answer1: '', template: '' })
// 模板相关
const templateOptions = ref<string[]>([])
const fetchTemplateList = async () => {
  try {
    const res = await axios.get('/conversation/mode')
    templateOptions.value = res.data?.data || []
  } catch (e) {
    templateOptions.value = []
  }
}
// 删除对话
const deletingConv = ref(false)



// 账号选择相关
const selectedAccount = ref('')
const accountOptions = ref<Account[]>([])
const accountsLoading = ref(false)

// 好友列表（模拟数据，实际应从API获取）
const friends = ref<Friend[]>([])

// 固定当前聊天所对应的设备ID（在选择好友时记住当时的账号ID）
const currentChatDeviceId = ref('')
// 固定当前聊天所对应的好友wx_id（避免 selectedFriend 被重置导致匹配失败）
const currentChatWxId = ref('')


// 过滤后的好友列表
const filteredFriends = computed(() => {
  if (!searchQuery.value) return friends.value
  return friends.value.filter(friend => 
    friend.nickname.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
    friend.remark?.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
    friend.tags?.some(tag => tag.toLowerCase().includes(searchQuery.value.toLowerCase()))
  )
})

// 排序后的好友列表
const sortedFriends = computed(() => {
  return [...filteredFriends.value].sort((a, b) => {
    // 置顶好友排在前面
    if (a.isTop && !b.isTop) return -1
    if (!a.isTop && b.isTop) return 1

    // 未读消息多的排在前面
    if (a.unreadCount > b.unreadCount) return -1
    if (a.unreadCount < b.unreadCount) return 1

    // 最后按时间排序
    const aTime = a.lastMessageTimestamp || a.timestamp || ''
    const bTime = b.lastMessageTimestamp || b.timestamp || ''
    return new Date(bTime).getTime() - new Date(aTime).getTime()
  })
})

// 获取在线账号列表
const fetchOnlineAccounts = async () => {
  accountsLoading.value = true
  try {
    const response = await axios.get('/wx_users')
    // 只保留在线账号
    const allAccounts = response.data.data || []
    accountOptions.value = allAccounts
      .filter((acc: any) => acc.status === 1) // 只保留在线账号
      .map((acc: any) => ({
        id: acc.device_id,
        name: acc.nickname,
        avatar: acc.avatar,
        status: 'online', // 既然已经过滤了，这里直接设为online
        auth_key: acc.auth_key
      }))
  } catch (error) {
    console.error('获取账号列表失败:', error)
    accountOptions.value = []
  } finally {
    accountsLoading.value = false
  }
}

// 处理账号选择变化
const enableSocket = import.meta.env.VITE_ENABLE_SOCKET === 'true'
let socketInstance: ReturnType<typeof socketService.connect> | null = null

const handleAccountChange = async () => {
  if (!selectedAccount.value) {
    friends.value = []
    selectedFriend.value = null
    chatMessages.value = []
    return
  }
  if (enableSocket) {
    socketInstance = socketService.connect(localStorage.getItem('token') || undefined)
  }
  await loadFriendsList()
  chatMessages.value = []
}

// 加载好友列表
const loadFriendsList = async () => {
  if (!selectedAccount.value) return
  try {
    const response = await axios.get('/wx_friends/history', {
      params: {
        device_id: selectedAccount.value
      }
    })
    const rawList = response.data.data || []
    friends.value = rawList.map((friend: any) => ({
      wx_id: friend.wx_id,
      nickname: friend.nickname,
      avatar: friend.avatar || '',
      status: 'online',
      lastMessage: friend.lastMessage || '',
      unreadCount: friend.unreadCount || 0,
      tags: friend.tags || [],
      isTop: friend.isTop || false,
      lastMessageTimestamp: friend.updated_at || '',
      timestamp: friend.created_at || '',
      remark: friend.remark || '' // 加载备注
    }))
  } catch (error) {
    ElMessage.error('获取好友列表失败')
    friends.value = []
  }
}

// 获取某个好友的未读消息数
const getUnreadForFriend = (wxId: string) => {
  if (!selectedAccount.value) return 0
  return messageStore.getUnread(selectedAccount.value, wxId)
}

// 当进入某个好友聊天时，清除未读
const selectFriend = async (friend: Friend) => {
  selectedFriend.value = friend
  // 记录选择该好友时所处的账号（设备）ID，用于后续消息匹配
  currentChatDeviceId.value = selectedAccount.value
  // 记录选择的好友wx_id
  currentChatWxId.value = friend.wx_id
  if (selectedAccount.value) {
    messageStore.clearUnread(selectedAccount.value, friend.wx_id)
  }

  if (selectedAccount.value && selectedAccount.value.startsWith('rag_')) {
    socketService.joinRoom(friend.wx_id)
  }

  await loadChatHistory(friend.wx_id, selectedAccount.value)
  await nextTick()
  scrollToBottom()
}

// 打开修改对话弹窗
const openEditDialog = async () => {
  if (!selectedAccount.value || !selectedFriend.value) {
    ElMessage.warning('请先选择账号和好友')
    return
  }
  qaForm.question1 = ''
  qaForm.answer1 = ''
  qaForm.template = ''
  await fetchTemplateList()
  editDialogVisible.value = true
}

// 保存修改对话
const saveEditedDialog = async () => {
  console.log('saveEditedDialog函数被调用')
  if (!qaForm.question1.trim() || !qaForm.answer1.trim()) {
    ElMessage.warning('请填写问题与答案')
    return
  }
  console.log('表单验证通过，开始保存')
  editSaving.value = true
  try {
    // 校验模板
    if (!qaForm.template) {
      ElMessage.warning('请选择模板')
      editSaving.value = false
      return
    }

    // 准备通用数据
    const formattedQuestion = `${qaForm.question1}`;
    const formattedAnswer = `${qaForm.answer1}`;

    const commonData = {
      questions: [formattedQuestion],
      answers: [formattedAnswer],
      template_name: qaForm.template
    }

    // 区分新增和更新操作
    if (currentEditingId.value) {
      // 更新操作
      // 注意：用户表示更新操作不应该调用/conversation/update接口
      // 但未提供正确的更新接口名称，此处暂不实现更新操作
      // 仅保留问答更新功能
      try {
        // 构建拼接文本: 问题+答案
        // const combinedText = `客户问：'${qaForm.question1}'，回答：${c}`;
        await axios.post('/v1/rag/update-text', {
          doc_id: currentEditingId.value,
          questions: [qaForm.question1],
          answers: [qaForm.answer1],
          category: qaForm.template
        })
        console.log('问答更新成功')
        ElMessage.success('问答更新成功')
      } catch (ragErr: any) {
        console.error('问答更新失败:', ragErr)
        ElMessage.warning('问答更新失败: ' + (ragErr.response?.data?.msg || ragErr.message))
      } finally {
        editSaving.value = false
        currentEditingId.value = ''  // 清空编辑ID
      }
      // 由于没有正确的更新接口，直接关闭对话框
      editDialogVisible.value = false
    } else {
      // 新增操作: 调用/conversation/update接口（尽管名称是update，但实际是新增接口）
      try {
        const payload = {
          ...commonData
        }
        const res = await axios.post('/conversation/update', payload)

        // 新增操作不需要调用v1/rag/update-texts接口
        console.log('对话新增成功，无需同步问答')
        if (res.data?.code === 200) {
          ElMessage.success('保存成功')
          currentEditingId.value = ''  // 清空编辑ID
          editDialogVisible.value = false
        } else {
          ElMessage.error(res.data?.msg || '保存失败')
        }
      } catch (err: any) {
        ElMessage.error('保存失败：' + (err.response?.data?.msg || err.message))
      } finally {
        editSaving.value = false
      }
    }
  } catch (error: any) {
    ElMessage.error('操作失败：' + (error.message || '未知错误'))
  } finally {
    console.log('saveEditedDialog函数finally块执行')
    editSaving.value = false
  }
}



// 删除当前对话
const handleDeleteConversation = async () => {
  if (!selectedAccount.value || !selectedFriend.value) {
    ElMessage.warning('请先选择账号和好友')
    return
  }
  try {
    await ElMessageBox.confirm('确定要删除当前对话吗？此操作不可恢复', '删除确认', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
  } catch {
    return
  }
  deletingConv.value = true
  try {
    const res = await axios.post('/v1/rag/del-context', {
      sender_id: selectedAccount.value,
      rec_id: selectedFriend.value?.wx_id || ''
    })
    if (res.data?.code === 200) {
      chatMessages.value = []
      ElMessage.success('已删除对话')
    } else {
      ElMessage.error(res.data?.msg || '删除失败')
    }
  } catch (err: any) {
    ElMessage.error('删除失败：' + (err.response?.data?.msg || err.message))
  } finally {
    deletingConv.value = false
  }
}

// 输入框回车发送（Shift+Enter 换行）
const handleEnterSend = (e: KeyboardEvent) => {
  if ((e as any).shiftKey) return
  sendMessage()
}

// AI开关处理函数
const handleAiToggle = async (val: string | number | boolean) => {
  const enabled = Boolean(val)
  aiEnabled.value = enabled
  if (enabled) {
    ElMessage.success('AI助手已开启')
    console.log('AI助手已开启，当前聊天将使用AI功能')
    await axios.post('/chat/unlock', {device_id: selectedAccount.value,wx_id: selectedFriend.value?.wx_id || ''})

  } else {
    ElMessage.info('AI助手已关闭')
    console.log('AI助手已关闭，当前聊天将使用普通模式')
    await axios.post('/chat/lock', {device_id: selectedAccount.value,wx_id: selectedFriend.value?.wx_id || ''})
  }
  
  // 可以在这里添加更多AI相关的逻辑
  // 比如通知后端AI状态变化，或者调整消息发送策略等
  if (selectedAccount.value && selectedFriend.value) {
    // 可以发送WebSocket消息通知后端AI状态变化
    // socketService.sendAiStatusChange({
    //   device_id: selectedAccount.value,
    //   wx_id: selectedFriend.value.wx_id,
    //   ai_enabled: enabled
    // })
  }
}

// 图片上传相关方法
const handleImageClick = () => {
  imageFileInput.value?.click()
}

const handleImageSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }

  // 验证文件大小（10MB）
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过10MB')
    return
  }

  await uploadAndSendImage(file)
  
  // 清空文件选择器
  target.value = ''
}

const uploadAndSendImage = async (file: File) => {
  if (!selectedFriend.value || !selectedAccount.value) {
    ElMessage.warning('请先选择账号和好友')
    return
  }

  uploadingImage.value = true
  let tempMessageId = ''
  
  try {
    // 创建临时消息显示上传状态
    const tempMessage: ChatMessage = {
      id: Date.now().toString(),
      content: '图片上传中...',
      timestamp: new Date().toISOString(),
      type: 3, // 图片消息
      is_sent: true,
      meta: {
        filename: file.name,
        size: file.size,
        mime: file.type
      }
    }
    
    tempMessageId = tempMessage.id
    chatMessages.value.push(tempMessage)
    await nextTick()
    scrollToBottom()

    // 获取当前账号的auth_key
    const currentAccount = accountOptions.value.find(acc => acc.id === selectedAccount.value)
    if (!currentAccount) {
      throw new Error('账号信息不存在')
    }

    // 上传图片
    const formData = new FormData()
    formData.append('file', file)
    formData.append('to_user_name', selectedFriend.value.nickname)

    const uploadResponse = await axios.post('/images', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (uploadResponse.data.code !== 200) {
      throw new Error(uploadResponse.data.msg || '图片上传失败')
    }

    const imageData = uploadResponse.data.data
    const imageUrl = imageData.url

    // 更新临时消息为实际图片URL
    const messageIndex = chatMessages.value.findIndex(msg => msg.id === tempMessageId)
    if (messageIndex !== -1) {
      chatMessages.value[messageIndex] = {
        ...tempMessage,
        content: imageUrl,
        meta: {
          width: imageData.width,
          height: imageData.height,
          size: imageData.size,
          filename: imageData.filename,
          mime: imageData.mime
        }
      }
    }

    // 发送图片消息
    if (currentAccount.auth_key === '123456') {
      // 测试账号，通过WebSocket发送
      socketService.sendMessage({
        type: 3,
        sender: selectedAccount.value,
        to_user: selectedFriend.value.wx_id,
        msg: imageUrl,
        auth_key: currentAccount.auth_key,
        temp_id: tempMessageId,
        ai_enabled: aiEnabled.value, // 添加AI状态
        meta: {
          width: imageData.width,
          height: imageData.height,
          size: imageData.size,
          filename: imageData.filename,
          mime: imageData.mime
        }
      })
    } else {
      // 正常账号，通过API发送
      const response = await axios.post('/wx_message/send', {
        to_users: [selectedFriend.value.wx_id],
        msg: imageUrl,
        auth_key: currentAccount.auth_key,
        type: 3, // 图片消息
        ai_enabled: aiEnabled.value, // 添加AI状态
        meta: {
          width: imageData.width,
          height: imageData.height,
          size: imageData.size,
          filename: imageData.filename,
          mime: imageData.mime
        }
      })

      if (response.data.code !== 200) {
        throw new Error('发送失败')
      }
    }

    ElMessage.success('图片发送成功')
    await nextTick()
    scrollToBottom()

  } catch (error: any) {
    console.error('图片上传或发送失败:', error)
    ElMessage.error('图片发送失败：' + (error.response?.data?.msg || error.message))
    
    // 移除失败的消息
    if (tempMessageId) {
      const messageIndex = chatMessages.value.findIndex(msg => msg.id === tempMessageId)
      if (messageIndex !== -1) {
        chatMessages.value.splice(messageIndex, 1)
      }
    }
  } finally {
    uploadingImage.value = false
  }
}
// 使用 toISOString 并手动调整时区
const adjustTimezone = (date: Date): string => {
  const timezoneOffset = new Date().getTimezoneOffset() * 60000
  return new Date(date.getTime() - timezoneOffset).toISOString()
};
// 加载聊天历史
const loadChatHistory = async (wxid: string, deviceIdOverride?: string) => {
  const deviceIdToUse = deviceIdOverride || selectedAccount.value
  if (!deviceIdToUse) {
    ElMessage.warning('请先选择账号')
    return
  }
  
  try {
    const response = await axios.get('/message/history', {
      params: {
        wx_id: wxid,
        device_id: deviceIdToUse,
        start_time: adjustTimezone(new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)), // 最近7天
        end_time: adjustTimezone(new Date())
      }
    })
    chatMessages.value = response.data.data || []
  } catch (error) {
    console.error('加载聊天历史失败:', error)
    ElMessage.error('加载聊天历史失败')
    chatMessages.value = []
  }
}

// 发送消息
const sendMessage = async () => {
  if (!messageInput.value.trim() || !selectedFriend.value || !selectedAccount.value) {
    if (!selectedAccount.value) {
      ElMessage.warning('请先选择账号')
    }
    return
  }

  sending.value = true
  try {
    const newMessage: ChatMessage = {
      id: Date.now().toString(),
      content: messageInput.value,
      timestamp: new Date().toISOString(),
      type: 1, // 文本消息
      is_sent: true
    }

    // 先添加到本地显示
    chatMessages.value.push(newMessage)
    messageInput.value = ''

    // 获取当前账号的auth_key
    const currentAccount = accountOptions.value.find(acc => acc.id === selectedAccount.value)
    if (!currentAccount) {
      throw new Error('账号信息不存在')
    }
    
    // 构建消息发送数据，包含AI状态
    const messageData = {
      type: 1,
      sender: selectedAccount.value,
      to_user: selectedFriend.value.wx_id,
      msg: newMessage.content,
      auth_key: currentAccount.auth_key,
      temp_id: newMessage.id, // 传递临时ID，用于后续更新状态
      ai_enabled: aiEnabled.value // 添加AI状态
    }

    if (currentAccount.auth_key === '123456') {
      // 表示当前是测试账号，用来对rag进行测试，将消息通过广播传递到后端中
      // 通过WebSocket发送消息
      socketService.sendMessage(messageData)
      requestAnimationFrame(() => scrollToBottom())
      return
    }
    
    // 调用发送API
    const response = await axios.post('/wx_message/send', {
      to_users: [selectedFriend.value.wx_id],
      msg: newMessage.content,
      auth_key: currentAccount.auth_key,
      type: 1,
      ai_enabled: aiEnabled.value // 添加AI状态到API请求
    })

    if (response.data.code !== 200) {
      ElMessage.error('发送失败')
      // 移除失败的消息
      chatMessages.value.pop()
    } else {
      ElMessage.success('发送成功')
      await nextTick()
      requestAnimationFrame(() => scrollToBottom())
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送失败')
    // 移除失败的消息
    chatMessages.value.pop()
  } finally {
    sending.value = false
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}



// 处理搜索结果选择
const handleSelectSearchedFriend = (item: Friend) => {
  // 若列表里不存在，先插入到顶部，便于后续显示
  const exists = friends.value.some(f => f.wx_id === item.wx_id)
  if (!exists) {
    friends.value.unshift(item)
  }
  selectFriend(item)
}

// 查询好友列表
const querySearchFriends = async (query: string, cb: (arg: any) => void) => {
  if (!selectedAccount.value) {
    cb([]);
    return;
  }
  try {
    const response = await axios.get('/wx_friends', {
      params: {
        device_id: selectedAccount.value,
        nickname: query || undefined
      }
    });
    const list = response.data.data || [];
    const results: Friend[] = list.map((it: any) => ({
      wx_id: it.wx_id,
      nickname: it.nickname || it.remark || it.wx_id,
      avatar: it.avatar || '',
      status: 'online',
      lastMessage: '',
      unreadCount: 0,
      tags: Array.isArray(it.tags) ? it.tags : [],
      isTop: false,
      lastMessageTimestamp: it.updated_at || '',
      timestamp: it.created_at || '',
      remark: it.remark || ''
    }))
    cb(results);
  } catch (error) {
    console.error('查询好友失败:', error);
    cb([]);
  }
};

// 格式化消息时间
const formatMessageTime = (timestamp: string) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diffMinutes = (now.getTime() - date.getTime()) / (1000 * 60)

  if (diffMinutes < 60) {
    return `${Math.floor(diffMinutes)}分钟前`
  } else if (diffMinutes < 24 * 60) {
    return `${Math.floor(diffMinutes / 60)}小时前`
  } else {
    return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes()}`
  }
}

// 获取消息类型文本
const getMessageTypeText = (type: number) => {
  const typeMap: Record<number, string> = {
    1: '文本',
    3: '图片',
    2: '语音',
    4: '视频',
    5: '文件',
    6: '位置',
    7: '名片',
    8: '链接',
    9: '小程序',
    10: '红包',
    11: '转账',
    12: '未知'
  }
  return typeMap[type] || '未知'
}

// 获取消息类型标签
const getMessageTypeTag = (type: number) => {
  const tagMap: Record<number, string> = {
    1: 'info',
    2: 'success',
    3: 'warning',
    4: 'danger',
    5: 'info',
    6: 'info',
    7: 'info',
    8: 'info',
    9: 'info',
    10: 'info',
    11: 'info',
    12: 'info'
  }
  return tagMap[type] || 'info'
}

// 预览图片
const previewImage = (url: string) => {
  // 使用浏览器原生的图片预览
  const newWindow = window.open(url, '_blank')
  if (!newWindow) {
    ElMessage.warning('无法打开图片预览，请检查浏览器弹窗设置')
  }
}

// 生成对话摘要
const generateSummary = async () => {
  if (!currentChatWxId.value || !currentChatDeviceId.value) {
    ElMessage.warning('请先选择一个会话');
    return;
  }

  try {
    const loadingInstance = ElMessage({ message: '正在生成摘要，请稍候...', showClose: false });
    const response = await axios.post('/message/description',
      {
        wx_id: currentChatWxId.value,
        device_id: currentChatDeviceId.value
      },
      {
        timeout: 120000
      }
    );
    
    loadingInstance.close();
    
    if (response.data.success && response.data.data) {
      // 显示摘要对话框
      ElMessageBox.alert(response.data.data, '对话摘要', {
        confirmButtonText: '确定',
        type: 'info',
        showClose: true,
        customClass: 'summary-dialog',
        dangerouslyUseHTMLString: false
      });
    } else {
      ElMessage.error('生成摘要失败：' + (response.data.message || '未知错误'));
    }
  } catch (error) {
    loadingInstance && loadingInstance.close();
    console.error('生成摘要时发生错误:', error);
    ElMessage.error('生成摘要失败，请重试');
  }
};

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = ''
  img.alt = '图片加载失败'
}

// 页面加载时获取好友列表
onMounted(async () => {
  // 连接 socket 并注册监听（若启用）
  if (enableSocket) {
    socketInstance = socketService.connect(localStorage.getItem('token') || undefined)
  }
  // 消息页监听 new_message 只处理聊天逻辑，不显示通知
  const onNewMessage = (payload: IncomingMessagePayload) => {
    console.log('消息页收到WebSocket消息:', payload)
    // 处理自己发送的消息
    if (payload.is_self_message) {
      // 如果是自己发送的消息，且当前聊天上下文匹配，则追加到聊天窗口
      if (currentChatDeviceId.value === payload.device_id && 
          currentChatWxId.value === payload.wx_id) {
        // 直接本地追加（保证即时可见）
        const newMsg = {
          id: Date.now().toString(),
          content: payload.content || '',
          timestamp: typeof payload.timestamp === 'number'
            ? new Date(payload.timestamp * 1000).toISOString()
            : payload.timestamp || new Date().toISOString(),
          type: Number(payload.type || 1),
          is_sent: true,
          meta: payload.meta || undefined
        }
        chatMessages.value.push(newMsg)
        ;(async () => {
          await nextTick()
          requestAnimationFrame(() => scrollToBottom())
        })()
        return
      } else {
        console.log('自己发送的消息不匹配当前聊天上下文，跳过处理')
        return
      }
    }

    const room = payload.room
    const fromWxId = payload.wx_id || payload.from || payload.from_user || room
    let resolvedDeviceId: string | undefined = payload.device_id
    if (!resolvedDeviceId && room && fromWxId === room) {
      // 好友房间广播（room 就是 wx_id），后端未带 device_id 的情况，使用当前会话的设备ID
      resolvedDeviceId = currentChatDeviceId.value
    }
    const deviceId = resolvedDeviceId || payload.room
    const content = payload.content || ''

    // 没有关联设备或发送者，忽略
    if (!deviceId || !fromWxId) {
      console.log('消息格式不完整，跳过:', { deviceId, fromWxId, content })
      return
    }

    // 如果当前没有选中好友或选中的不是该好友，则只更新未读计数
    if (!currentChatWxId.value || currentChatWxId.value !== fromWxId || currentChatDeviceId.value !== deviceId) {

      // 更新好友列表中的未读计数与最后消息
      const friend = friends.value.find(f => f.wx_id === fromWxId)
      if (friend) {
        friend.unreadCount = (friend.unreadCount || 0) + 1
        // 根据消息类型显示不同的最后消息
        const messageType = Number(payload.type || 1)
        if (messageType === 3) {
          friend.lastMessage = '[图片]'
        } else {
          friend.lastMessage = content
        }
        // 处理时间戳：如果是Unix时间戳则转换
        const timestamp = typeof payload.timestamp === 'number' 
          ? new Date(payload.timestamp * 1000).toISOString()
          : payload.timestamp || new Date().toISOString()
        friend.lastMessageTimestamp = timestamp
      }
      // 不显示通知，由监控页统一处理
      return
    }

    // 匹配当前会话：本地直接追加，确保即时可见
    const newMsg = {
      id: Date.now().toString(),
      content: content,
      timestamp: typeof payload.timestamp === 'number'
        ? new Date(payload.timestamp * 1000).toISOString()
        : payload.timestamp || new Date().toISOString(),
      type: Number(payload.type || 1),
      is_sent: false,
      meta: payload.meta || undefined
    }
    chatMessages.value.push(newMsg)
    ;(async () => {
      await nextTick()
      requestAnimationFrame(() => scrollToBottom())
    })()
  }

  // 确保不会拿旧实例的闭包：先移除旧处理器，再绑定新处理器
  const KEY = '__message_on_new_message_handler__'
  if (enableSocket && socketInstance) {
    const oldHandler = (window as any)[KEY]
    if (oldHandler) {
      socketInstance.off('new_message', oldHandler)
    }
    socketInstance.on('new_message', onNewMessage)
    ;(window as any)[KEY] = onNewMessage
  }

  await fetchOnlineAccounts()
  if (accountOptions.value.length > 0) {
    selectedAccount.value = accountOptions.value[0].id
    await handleAccountChange()
  }
})

onBeforeUnmount(() => {
  if (!enableSocket) return
  // 不自动离开房间，由监控页控制
  if (!socketInstance) {
    socketInstance = socketService.connect(localStorage.getItem('token') || undefined)
  }
  if (!socketInstance) return
  const KEY = '__message_on_new_message_handler__'
  const oldHandler = (window as any)[KEY]
  if (oldHandler) {
    socketInstance.off('new_message', oldHandler)
    ;(window as any)[KEY] = undefined
  }
})
</script>

<style scoped lang="scss">


.message-container {
  height: calc(100vh - 120px);
  
  .chat-layout {
    display: flex;
    height: 100%;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    overflow: hidden;
  }

  .friend-list {
    width: 300px;
    border-right: 1px solid #e4e7ed;
    display: flex;
    flex-direction: column;

    .list-header {
      padding: 16px;
      border-bottom: 1px solid #e4e7ed;
      
      .account-selector {
        margin-bottom: 12px;
        
        .account-option {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .account-avatar {
            flex-shrink: 0;
          }
          
          .account-status {
            margin-left: auto;
          }
        }
        
        .empty-data {
          text-align: center;
          padding: 10px 0;
          color: #909399;
        }
      }
      
      h3 {
        margin: 0 0 12px 0;
        font-size: 16px;
        font-weight: 600;
      }
    }

    .friend-items {
      flex: 1;
      overflow-y: auto;

      .friend-item {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        cursor: pointer;
        border-bottom: 1px solid #f5f5f5;
        transition: background-color 0.2s;

        &:hover {
          background-color: #f5f7fa;
        }

        &.active {
          background-color: #ecf5ff;
          border-right: 3px solid #409eff;
        }

        &.top {
          background-color: #f0f9eb; /* 置顶好友背景色 */
          border-right: 3px solid #67c23a; /* 置顶好友边框色 */
        }

        .friend-info {
          flex: 1;
          margin-left: 12px;
          overflow: hidden;

          .friend-name {
            font-weight: 500;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .last-message {
            font-size: 12px;
            color: #909399;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }

        .unread-badge {
          margin-left: 8px;
        }

        .top-icon {
          margin-left: 8px;
          color: #409eff; /* 置顶图标颜色 */
        }
      }
    }
  }

  .chat-area {
    flex: 1;
    display: flex;
    flex-direction: column;

    .chat-header {
      padding: 16px;
      border-bottom: 1px solid #e4e7ed;
      background-color: #fafafa;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .chat-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 500;
      }

      .header-actions {
        display: flex;
        gap: 8px;
      }
    }

    .chat-messages {
      flex: 1;
      overflow-y: auto;
      padding: 16px;
      background-color: #f5f5f5;

      .no-chat,
      .no-messages {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
      }

      .messages-list {
        .message-item {
          display: flex;
          flex-direction: column;
          margin-bottom: 16px;

          .message-time {
            font-size: 12px;
            color: #909399;
            margin-bottom: 4px;
            text-align: center;
          }

          .message-content {
            display: flex;
            align-items: flex-start;
            gap: 8px;
            max-width: 70%;
            word-break: break-word;
          }

          &.sent {
            align-items: flex-end;

            .message-content {
              background-color: #e1f3d8;
              color: #389e0d;
              padding: 8px 12px;
              border-radius: 8px;
              flex-direction: row-reverse;
            }
          }

          &.received {
            align-items: flex-start;

            .message-content {
              background-color: #ffffff;
              color: #303133;
              padding: 8px 12px;
              border-radius: 8px;
            }
          }

          .message-type {
            margin-top: 4px;
          }

                     .message-image {
             position: relative;
             display: flex;
             align-items: center;
             justify-content: center;
             min-width: 100px;
             min-height: 100px;
             max-width: 300px;
             max-height: 300px;
             background-color: #f8f9fa;
             border-radius: 8px;
             overflow: hidden;
             border: 1px solid #e4e7ed;

             .chat-image {
               max-width: 100%;
               max-height: 100%;
               object-fit: contain;
               transition: transform 0.2s ease;

               &:hover {
                 transform: scale(1.05);
               }
             }

             .upload-status {
               position: absolute;
               top: 50%;
               left: 50%;
               transform: translate(-50%, -50%);
               background-color: rgba(0, 0, 0, 0.7);
               color: #fff;
               padding: 8px 12px;
               border-radius: 6px;
               display: flex;
               align-items: center;
               gap: 8px;
               font-size: 12px;
               z-index: 10;
               backdrop-filter: blur(4px);
             }
           }
        }
      }
    }

    .chat-input {
      border-top: 1px solid #e4e7ed;
      background-color: #ffffff;

      .input-toolbar {
  padding: 8px 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  gap: 8px;
  align-items: center;
}

.switch-container {
  margin-left: auto;
  display: flex;
  align-items: center;
}

      .input-area {
        padding: 16px;
        display: flex;
        gap: 12px;
        align-items: flex-end;

        .el-textarea {
          flex: 1;
        }

        .el-button {
          height: 32px;
          padding: 0 16px;
        }
      }
    }
  }
}
</style>
